<template>
  <div class="login">
    <el-col :span="8" class="box">
            <el-card shadow="hover">
                <h4>后台登录系统</h4>
                <el-form ref="form" :model="form" :rules="rulesForm">
                <el-form-item prop="username">
                    <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input placeholder="请输入密码" type="password" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loginFn" style="width: 100%;">登录</el-button>
                    <el-link type="info" style="float: left;" @click="$router.push('/reg')">去注册</el-link>
                </el-form-item>
                </el-form>
            </el-card>
        </el-col>
  </div>
</template>

<script>
import { loginApi } from '@/api'
import { mapMutations, mapState } from 'vuex'
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rulesForm: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z0-9]{1,10}$/,
            message: '用户名必须是1-10的大小写字母数字',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15的非空字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    ...mapState(['token']),
    ...mapMutations(['updateToken']),
    loginFn () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          // console.log(this.form)
          const { data: res } = await loginApi(this.form)
          // console.log(res)
          if (res.code !== 0) {
            return this.$message.error(res.message)
          }
          this.$message.success(res.message)
          this.updateToken(res.token)
          this.$router.push('/')
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .login{
        display: flex;
        justify-content: center;
        margin-top: 100px;
        text-align: center;

    }
</style>
